using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;

namespace TmxUtil
{
    public class SisulizerComparer
    {
        public static void CompareToSisulizer(Solution solution)
        {
            using (FileStream fs = new FileStream(Path.GetFileNameWithoutExtension(solution.SlnFile) + ".compare", FileMode.Create, FileAccess.Write, FileShare.Read))
            using (StreamWriter writer = new StreamWriter(fs, Encoding.Default))
            {
                string stmxFile =
                    Path.Combine(
                        new FileInfo(solution.SlnFile).DirectoryName,
                        Path.GetFileNameWithoutExtension(solution.SlnFile) + ".stmx");

                if (!File.Exists(stmxFile))
                {
                    string info1 = "Sisulizer tmx file '" + stmxFile + "' not found";
                    writer.WriteLine(info1);
                    Console.WriteLine(info1);
                    return;
                }

                Console.WriteLine("Compare to sisulizer tmx: " + stmxFile);

                XmlDocument doc = new XmlDocument();
                doc.Load(stmxFile);

                SisulizerUtil.ItemCollection sitems = SisulizerUtil.ReadAll(doc);
                foreach(SisulizerUtil.Item item in sitems)
                {
                    // writer.WriteLine("{0} {1}: {2}", item.Language, item.Context, item.Value);
                }

                ResXCollection resXlist = new ResXCollection();
                foreach(Project p in solution.Projects)
                    resXlist.AddRange(p.ResXList);

                resXlist.Fix();
                resXlist.Sort();

                resXlist = new ResXCollection(resXlist.FindByCulture(string.Empty));

                int total1 = 0, total2 = 0;
                foreach(ResX resX in resXlist)
                {
                    bool has = false;
                    ResXStrings strings = resX.Strings;
                    foreach(string localKey in strings.Keys)
                    {
                        SisulizerUtil.Item sitem = sitems.Find(resX, localKey);
                        if (sitem == null)
                        {
                            total2++;
                            if (!has)
                            {
                                writer.WriteLine("Resource {0} :: {1}", resX.Project.File, resX.File);
                                has = true;
                                total1++;
                            }
                            writer.WriteLine("  {0}:  {1}", localKey, resX.Strings[localKey] );
                        }
                    }

                    if (has)
                        writer.WriteLine();

                }

                writer.WriteLine("Total lost items: {0} (at {1} resources)", total2, total1);
            }
        }
    }
}
